﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ENG.TeachersDiary.Model;

namespace ENG.TeachersDiary
{
  public partial class FrmMarkGroups : Form
  {
    DiaryDB db = null;
    Subject currentSubject;

    public FrmMarkGroups()
    {
      InitializeComponent();
    }

    public void ReDB()
    {
      db = Common.DBConn;
      currentSubject = Common.GetCurrentSubject(db);

      this.Text = Properties.Resources.MarkGroupsForSubject + " " + currentSubject.Title;
      grd.DataSource = currentSubject.MarkGroups;
      grd.Sort(grd.Columns[grd.GetPropertyRowIndex("OrderIndex")], ListSortDirection.Ascending);
    }

    private void FrmMarkGroups_Load(object sender, EventArgs e)
    {
      ReDB();
    }

    private void grd_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
      db.SubmitChanges();
    }

    private void grd_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
    {
      Model.MarkGroup mg = (Model.MarkGroup)e.Row.DataBoundItem;

      if (mg.IsDefault)
      {
        MessageBox.Show(Properties.Resources.DefaultMarkGroupCannotBeDeleted, 
          Properties.Resources.ErrorDialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
        e.Cancel = true;
        return;
      }
      else if (mg.Marks.Count > 0)
      {
        MessageBox.Show(Properties.Resources.NonEmptyMarkGroupCannotBeDeleted,
          Properties.Resources.ErrorDialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
        e.Cancel = true;
        return;
      }
      else
      {
        db.MarkGroups.DeleteOnSubmit(mg);
        db.SubmitChanges();
      }
    }

    private void grd_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
    {
      e.Row.Cells[grd.GetPropertyRowIndex("IsToOffer")].Value = true;
      e.Row.Cells[grd.GetPropertyRowIndex("IsDefault")].Value = false;
      e.Row.Cells[grd.GetPropertyRowIndex("IsEvaluated")].Value = true;
      e.Row.Cells[grd.GetPropertyRowIndex("SubjectID")].Value = currentSubject.SubjectID;
      e.Row.Cells[grd.GetPropertyRowIndex("Weight")].Value = 1;
    }

    private void FrmMarkGroups_FormClosing(object sender, FormClosingEventArgs e)
    {
      db.SubmitChanges();
    }
  }
}
